package com.vehicle.inspection.api

import android.util.Base64
import com.zhida.jiyangcenter.BuildConfig
import com.zhida.jiyangcenter.utils.SP
import okhttp3.*
import okio.Buffer
import java.io.IOException
import java.io.UnsupportedEncodingException
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException
import java.util.*
import java.util.regex.Pattern
import kotlin.collections.HashMap


class BaseTokenInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val oldRequest = chain.request()
        val method = oldRequest.method()
        val body = oldRequest.body()
        val authorizeUrlBuilder = oldRequest.url().newBuilder()
                .scheme(oldRequest.url().scheme())
                .host(oldRequest.url().host())

        val newBody: RequestBody? = when (body) {
            is FormBody -> {
                val formParams = HashMap<String, String>().apply { for (i in 0 until body.size()) this[body.name(i)] = body.value(i) }

                FormBody.Builder().apply {
                    formParams.forEach { addEncoded(it.key, it.value) }
                    addEncoded("key_id", SP.key_id.get().toString())
                    addEncoded("version", BuildConfig.VERSION_CODE.toString())
                    addEncoded("login_account", SP.account.get().toString())
                }.build()
            }
            is MultipartBody -> {
                val newBody = MultipartBody.Builder().apply {
                    body.parts().forEach { addPart(it) }
                }.setType(MultipartBody.FORM)
                val params = HashMap<String, String>()
                body.parts().forEach {
                    if (it.body().contentType()?.type()?.contains("text") == true) {
                        val headers = it.headers()
                        for (i in 0 until headers!!.names().size) {
                            val value = headers.value(i)//valueform-data; name="article_type"
                            val replaceValue = "form-data; name="//这段在MultipartBody.Part源码中看到
                            if (value.contains(replaceValue)) {
                                val key = value.replace(replaceValue, "").replace("\"".toRegex(), "")
                                params[key] = bodyToString(it.body())
                                break
                            }
                        }
                    }
                }
                newBody.addPart(Headers.of("Content-Disposition", "form-data; name=\"key_id\"",
                        "Content-Transfer-Encoding", "binary"),
                    SP.key_id.get().toString().toRequestBody())
                        .addPart(Headers.of("Content-Disposition", "form-data; name=\"version\"",
                                "Content-Transfer-Encoding", "binary"),
                                BuildConfig.VERSION_CODE.toString().toRequestBody())
                        .addPart(Headers.of("Content-Disposition", "form-data; name=\"login_account\"",
                                "Content-Transfer-Encoding", "binary"),
                            SP.account.get().toString().toRequestBody())
                                .build()
            }
            else -> {
                if ("POST" == method || "PUT" == method || "DELETE" == method || "PATCH" == method) {
                    val map = doForm(oldRequest)
                    FormBody.Builder().apply {
                        map?.forEach { addEncoded(it.key, it.value) }
                        addEncoded("key_id", SP.key_id.get().toString())
                        addEncoded("version", BuildConfig.VERSION_CODE.toString())
                        addEncoded("login_account",  SP.account.get().toString())
                    }.build()
                } else {
                    val params = HashMap<String, String>()
                    val url = oldRequest.url()
                    val iterator = url.queryParameterNames().iterator()
                    var i = 0
                    while (iterator.hasNext()) {
                        params[iterator.next()] = url.queryParameterValue(i)
                        i++
                    }
                    authorizeUrlBuilder.addQueryParameter("key_id", SP.key_id.get().toString())
                            .addEncodedQueryParameter("version", BuildConfig.VERSION_CODE.toString())
                            .addQueryParameter("login_account", SP.account.get().toString())
                    null
                }
            }
        }
        val request = oldRequest.newBuilder().url(authorizeUrlBuilder.build()).apply {
            if (newBody != null) post(newBody)
            else if (oldRequest.body() != null) post(oldRequest.body()!!)
        }.headers(oldRequest.headers()).build()
        return chain.proceed(request)
    }

    /**
     * 获取表单的请求参数
     * @param request
     * @return
     */
    private fun doForm(request: Request): Map<String, String>? {
        var params: MutableMap<String, String>? = null
        var body: FormBody? = null
        try {
            body = request.body() as FormBody?
        } catch (c: ClassCastException) {
        }

        if (body != null) {
            val size = body.size()
            if (size > 0) {
                params = java.util.HashMap()
                for (i in 0 until size) {
                    params[body.name(i)] = body.value(i)
                }
            }
        }
        return params
    }

    private fun bodyToString(request: RequestBody?): String {
        try {
            val buffer = Buffer()
            if (request != null)
                request.writeTo(buffer)
            else
                return ""
            return buffer.readUtf8()
        } catch (e: IOException) {
            return "did not work"
        }
    }
}
fun String.toRequestBody(): RequestBody {
    return RequestBody.create(MediaType.parse("text/plain"), this)
}